// 引入模块
const Koa = require('koa');
const fs = require('fs');
const path = require('path');
const router = require('koa-router')();
const koaBody = require('koa-body');
const static = require('koa-static');
const send = require('koa-send');
const mime = require('mime-types');//一旦前端请求有mime类型报错就可以用它


// 实例化
const app = new Koa();
 
app.use(koaBody());
 
router.get('/', (ctx) => {
  // 设置头类型, 如果不设置，会直接下载该页面
  ctx.type = 'html';
  // 读取文件
  const pathUrl = path.join(__dirname, '/static/download.html');
  ctx.body = fs.createReadStream(pathUrl);
});
 
router.get('/download/:name', async (ctx) => {
  const name = ctx.params.name;
  const filePath = `static/upload/images/${name}`;

  ctx.attachment(filePath);
  await send(ctx, filePath);
});
 

/*
 
 //后端读取图片给前端展示
 app.use(async (ctx) => {

	let filePath = path.join(__dirname, ctx.url); //图片地址
	let file = null;
	try {
	    file = fs.readFileSync(filePath); //读取文件
	} catch (error) {
		//如果服务器不存在请求的图片，返回默认图片
	    filePath = path.resolve(__dirname, './static/upload/images/default.png'); //默认图片地址
	    file = fs.readFileSync(filePath); //读取文件	    
	}

	let mimeType = mime.lookup(filePath); //读取图片文件类型
	ctx.set('content-type', mimeType); //设置返回类型
	ctx.body = file; //返回图片

});

*/
 
 
// 配置静态资源路径
app.use(static(path.join(__dirname)));
 
// 启动路由
app.use(router.routes()).use(router.allowedMethods());
 
// 监听端口号
app.listen(3001, () => {
  console.log('server is listen in 3001');

});